#include "HeadFile.h"

char* FileOperation::path = const_cast<char*>("user_list.txt");
int FileOperation::list_longth = 0;
FileOperation* FileOperation::instance = nullptr;

int FileOperation::ReturnLen()
{
	list_longth = 0;
	char temp[255];
	FILE* file = nullptr;
	fopen_s(&file, path, "r");
	while (fgets(temp, 255, file))
	{
		if(temp[0]!='\n')
			list_longth++;
	}
	fclose(file);
	return list_longth;
}

void FileOperation::ReadInNode(int num,UserNode* node)
{
	char temp[255];
	FILE* file = nullptr;
	fopen_s(&file, path, "r");
	for (int i = 0; i < list_longth; i++)
	{
		if (i == num)
		{
			fscanf_s(file, "%s %s %s", node->name, 20, node->occupational, 10, node->phone, 12);
			break;
		}
		else
			fgets(temp, 255, file);
	}
	fclose(file);
}

void FileOperation::WriteFile(UserNode** user_list, int length)
{
	FILE* file = nullptr;
	fopen_s(&file, path, "w");
	for (int i = 0; i < length; i++)
	{
		fprintf_s(file, "%s %s %s\n", user_list[i]->name, user_list[i]->occupational, user_list[i]->phone);
	}
	fclose(file);
}

void FileOperation::AttandFile(UserNode* node)
{
	FILE* file = nullptr;
	fopen_s(&file, path, "a");
	fprintf_s(file, "%s %s %s\n", node->name, node->occupational, node->phone);
	fclose(file);
}

FileOperation * FileOperation::Instance()
{
	if (instance == nullptr)
	{
		instance = new FileOperation;
	}
	return instance;
}
